package com.ys.peony.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.ys.peony.R;
import com.ys.peony.app.BaseApplication;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.UserModel;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.R.attr.delay;

/**
 * 描述：价格相关计算工具类
 * Created by yukang on 2017/7/31.
 */

public class YsUtil {

    private final static int DEFAULT_DIGIT = 2;//价格默认保留小数点后两位;

    public static boolean isValidNetWordAndUser() {
        UserModel userModel = SharePreferencesUtils.getInstance().getUserModel();
        if (null == userModel) {
            ToastUtils.showToast("用户信息为空");
            return false;
        }

        if (!NetUtils.isNetworkConnected(BaseApplication.getInstance())) {
            ToastUtils.showToast(BaseApplication.getInstance().getResources().getString(R.string.no_net_error));
            return false;
        }
        return true;
    }

    /*时间戳转换成字符窜*/
    public static String getDateToString(long time) {
        Date d = new Date(time);
        SimpleDateFormat sf = null;
        sf = new SimpleDateFormat("yyyy-MM-dd");
        return sf.format(d);
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }

    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {
        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 控制窗口背景的不透明度
     *
     * @param activity 上下文
     * @param alpha    不透明度
     */
    public static void setWindowBackgroundAlpha(Activity activity, float alpha) {
        Window window = activity.getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.alpha = alpha;
        window.setAttributes(layoutParams);
    }

    /**
     * 获取状态栏高度＋标题栏高度
     *
     * @param activity
     */
    public static int getTopBarHeight(Activity activity) {
        return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
    }

    /**
     * 判断屏幕横屏/竖屏
     *
     * @param context
     * @return 返回true表示：横屏；返回false表示：竖屏
     */
    public static boolean isScreenOrientation(Context context) {
        //获取设置的配置信息
        Configuration config = context.getResources().getConfiguration();

        return (config.orientation == Configuration.ORIENTATION_LANDSCAPE) ? true : false;
    }

    /**
     * 提供精确的加法运算。
     *
     * @param v1 被加数
     * @param v2 加数
     * @return 两个参数的和
     */
    public static BigDecimal add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * @param list
     * @return 返回所有相加总和
     */
    public static BigDecimal addAll(List<BigDecimal> list) {
        if(list == null || list.size() < 1) {
            return null;
        }
        BigDecimal all = list.get(0);
        for (int i = 1; i < list.size(); i++) {
            all = all.add(list.get(i));
        }
        return all;
    }
    /**
     * @param list ：价格列表
     * @param digit ：保留小数点后位数
     * @return 返回所有相加总和
     */
    public static String addAll(List<BigDecimal> list,int digit) {
        if(list == null || list.size() < 1) {
            return "";
        }
        BigDecimal all = list.get(0);
        for (int i = 1; i < list.size(); i++) {
            all = all.add(list.get(i));
        }
        return all.setScale(digit, BigDecimal.ROUND_HALF_UP).toString();
    }

    public static String scaleDecimal(BigDecimal bigDecimal,int digit) {
        if(bigDecimal == null) {
            return "";
        }
        return bigDecimal.setScale(digit, BigDecimal.ROUND_HALF_UP).toString();
    }

    public static String scaleDecimal(BigDecimal bigDecimal) {
        return scaleDecimal(bigDecimal,DEFAULT_DIGIT);
    }

    /**
     * 提供（相对）精确的除法运算，当发生除不尽的情况时，精确到
     * 小数点以后10位，以后的数字四舍五入。
     * @param v1 被除数
     * @param v2 除数
     * @return 两个参数的商
     */
    public static String div(BigDecimal v1,BigDecimal v2){
        return div(v1,v2,DEFAULT_DIGIT);
    }
    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指
     * 定精度，以后的数字四舍五入。
     * @param v1 被除数
     * @param v2 除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static String div(BigDecimal v1,BigDecimal v2,int scale){
        if(scale<0){
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        return v1.divide(v2,scale,BigDecimal.ROUND_HALF_UP).toString();
    }

    /**
     * 描述：分数字符串转小数
     * @param data
     */
    public static float fenshuToDecimals(String data) {
        if(TextUtils.isEmpty(data)) {
            return YSConstant.INVALID;
        }
        String[] s = data.split("/");
        if (s != null && s.length == 2) {
            float a = Float.valueOf(s[0]);
            float b = Float.valueOf(s[1]);
            return (a / b * 1.00f);
        }
        return YSConstant.INVALID;
    }

    /**
     * 描述：获取字符串分数分子，分母值
     * @param data
     * @return
     */
    public static int[] getfenshu(String data) {
        if(TextUtils.isEmpty(data)) {
            return null;
        }
        String[] s = data.split("/");
        if (s != null && s.length == 2) {
            int a = Integer.valueOf(s[0]);
            int b = Integer.valueOf(s[1]);
            int [] result = {a,b};
            return result;
        }
        return null;
    }

    public static String requestVerifyCode(String phone) {
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        final String randNum = CommonUtils.getRandNum(1, 999999);
        builder.setType(MultipartBody.FORM)
                .addFormDataPart("mobile", phone)
                .addFormDataPart("param", randNum)
                .addFormDataPart("tempId", "15");
        RequestBody requestBody = builder.build();
        httpManagerUtils.post(HttpURL.verifyCode, requestBody, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                int i = 1;
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);

            }
        });
        return randNum;
    }


}
